<?php
declare(strict_types=1);

namespace App\Controller\Admin\V1\Paper;

use App\Controller\Admin\AdminController;
use App\Model\PaperQuestion;
use App\Repositories\PaperQuestionRepository;
use App\Repositories\UserRepository;
use App\Request\StoreQuestionRequest;

class QuestionController extends AdminController
{
    public function types()
    {
        $datas = PaperQuestion::getLabels('type');
        $return_type=[];
        foreach ($datas as $key=>$val){
            $obj=[
                'name' => $val,
                'value' => $key
            ];
            $return_type=array_merge($return_type,[$obj]);
        }
        return $this->response->success($return_type);
    }

    public function list(){
        $name = $this->request->input('title',null);
        $rows = $this->request->input('rows',10);
        $paper_id = $this->request->input('paper_id',0);
        $search=[];
        if($name){
            $search['name']=[
                'field' => 'title',
                'value' => $name,
                'method' => 'like'
            ];
        }
        $search['paper_id']=[
            'field' => 'paper_id',
            'value' => $paper_id
        ];
        $orderBy= [
            [
                'field' => 'listorder',
                'sort' => 'asc'
            ],
            [
                'field' => 'id',
                'sort' => 'desc'
            ]
        ];
        $datas = PaperQuestionRepository::getInstance()->getList('*',$search,['limit'=>$rows],$orderBy);
        return $this->response->success($datas);
    }

    public function detail(){
        $id = $this->request->input('id');
        $question = PaperQuestionRepository::getInstance()->getById($id);
        return $this->response->success($question);
    }

    public function delete(){
        $id = $this->request->input('id');
        $result = PaperQuestionRepository::getInstance()->delete($id);
        if($result){
            return $this->response->success($result['data']);
        }
        return $this->response->error(10000,$result['msg']);
    }


    public function store(StoreQuestionRequest $request){
        $params = $request->all();
        $admin = $this->request->getAttribute('admin');
        $params['admin_id'] = $admin->id;
        $result = PaperQuestionRepository::getInstance()->store($params);
        if($result['success']){
            return $this->response->success([
                'id' => $result['data']->id
            ]);
        }
        return $this->response->error(10000,$result['msg']);
    }


}